<template>
  <div class="login_container">
    <el-row>
      <el-col
        :span="12"
        :xs="0"
      ></el-col>
      <el-col
        :span="12"
        :xs="24"
      >
        <el-form
          ref="loginFormRef"
          class="login_form"
          :model="loginForm"
          :rules="loginRules"
        >
          <h1>Hello</h1>
          <h2>欢迎来到硅谷甄选</h2>
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              type="text"
            >
              <!-- 通过插槽自定义图标样式 -->
              <template #prefix>
                <i-ep-user />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              show-password
            >
              <!-- 通过插槽自定义图标样式 -->
              <template #prefix>
                <i-ep-lock />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="default"
              class="login_btn"
              :loading="loading"
              @click="login"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
        <el-avatar
          icon="el-icon-user-solid"
          size="large"
          shape="circle"
          fit="fill"
        ></el-avatar>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import useUserStore from '@/stores/modules/user';
import { useRouter } from 'vue-router';
import { getTime } from '@/utils/time';

// 登录按钮加载状态，默认为false
let loading = ref(false);
let $router = useRouter();
let useStore = useUserStore();
let loginFormRef = ref();

// 登录表单数据
let loginForm = reactive({
  username: 'admin',
  password: '1111111',
});

// 常规登录表单校验规则
// const loginRules = reactive({
//   username: [
//     { required: true, message: '请输入用户名', trigger: 'change' },
//     {
//       required: true,
//       min: 5,
//       max: 16,
//       message: '用户名长度为5-16位',
//       trigger: 'change',
//     },
//   ],
//   password: [
//     { required: true, message: '请输入密码', trigger: 'blur' },
//     {
//       required: true,
//       min: 6,
//       max: 16,
//       message: '密码长度为6-16位',
//       trigger: 'change',
//     },
//   ],
// });

// 自定义校验规则的函数
const validatorUsername = (_rule, value, callback) => {
  // rule: 当前校验规则对象
  // value: 当前表单的值
  // 函数: 如果符合条件 callback 房型通过，否则 callback 抛出错误信息
  if (value.length < 5 || value.length > 16) {
    callback(new Error('账号长度至少为5-16位'));
  } else {
    callback();
  }
};
const validatorPassword = (_rule, value, callback) => {
  if (value.length < 6 || value.length > 24) {
    callback(new Error('密码长度为至少为6-24位'));
  } else {
    callback();
  }
};

// 自定义登录表单校验规则
const loginRules = reactive({
  username: [{ validator: validatorUsername, trigger: 'change' }],
  password: [{ validator: validatorPassword, trigger: 'change' }],
});

/**
 * 异步登录函数
 * 使用尝试-捕获机制处理登录过程中的异步操作和可能的错误
 */
const login = async () => {
  // 保证全部表单校验通过再发送请求
  await loginFormRef.value.validate();

  // 登录按钮开始加载
  loading.value = true;
  try {
    // 保证登录成功
    await useStore.userLogin(loginForm);
    // 编程式导航跳转至首页
    $router.push('/');
    // 登录成功的提示信息
    ElNotification({
      title: getTime(),
      message: '欢迎回来',
      type: 'success',
      duration: 2000,
    });
    loading.value = false;
  } catch (error) {
    // 登录失败的提示信息
    ElNotification({
      title: '登录失败',
      message: (error as Error).message,
      type: 'error',
      duration: 2000,
    });
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.login_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover;
}
.login_form {
  position: relative;
  width: 80%;
  top: 30vh;
  background: url('@/assets/images/login_form.png') no-repeat;
  background-size: cover;
  padding: 40px;
  h1 {
    color: #fff;
    font-size: 40px;
  }
  h2 {
    color: #fff;
    font-size: 20px;
    margin: 20px 0;
  }
  .login_btn {
    width: 100%;
  }
}
</style>
